// pages/discover/recipe/detail/index.js
const { api } = require("../../../../utils/api.js");
const logger = require("../../../../utils/logger.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    recipeId: null,
    recipe: null,
    loading: true,
    quantity: 1,
    totalPrice: 0,
    basePrice: 0,
    showOrderPanel: false,
    priceFromParams: null,
    priceSource: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('菜谱详情页收到参数:', options);
    const recipeId = options.id;
    const priceFromParams = options.price ? parseFloat(options.price) : null;
    const priceSource = options.priceSource || null;
    
    if (!recipeId) {
      wx.showToast({
        title: '菜谱ID不能为空',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
      return;
    }

    this.setData({ 
      recipeId,
      priceFromParams,
      priceSource
    }, () => {
      this.getRecipeDetail(recipeId);
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 获取菜谱详情
  getRecipeDetail(recipeId) {
    this.setData({ loading: true });
    
    api.getRecipeDetail(recipeId).then(res => {
      if (res.code === 200 && res.data) {
        // 使用传入的价格或计算基本价格
        let basePrice;
        if (this.data.priceFromParams !== null) {
          console.log('使用URL参数中的价格:', this.data.priceFromParams);
          basePrice = this.data.priceFromParams;
        } else {
          console.log('计算基础价格');
          basePrice = this.calculateBasePrice(res.data);
        }
        
        // 如果数据中有价格字段且没有从参数获取价格，则使用数据中的价格
        if (res.data.price && this.data.priceFromParams === null) {
          basePrice = parseFloat(res.data.price);
          console.log('使用API返回的价格:', basePrice);
        }
        
        this.setData({
          recipe: res.data,
          loading: false,
          basePrice: basePrice,
          totalPrice: (basePrice * this.data.quantity).toFixed(1)
        });
      } else {
        throw new Error('获取菜谱详情失败');
      }
    }).catch(err => {
      console.error('获取菜谱详情失败:', err);
      
      // 使用模拟数据
      const mockRecipe = this.getMockRecipeDetail(recipeId);
      
      // 使用传入的价格或模拟数据的价格
      let basePrice;
      if (this.data.priceFromParams !== null) {
        console.log('使用URL参数中的价格:', this.data.priceFromParams);
        basePrice = this.data.priceFromParams;
      } else if (mockRecipe.price) {
        console.log('使用模拟数据中的价格:', mockRecipe.price);
        basePrice = parseFloat(mockRecipe.price);
      } else {
        console.log('计算基础价格');
        basePrice = this.calculateBasePrice(mockRecipe);
      }
      
      this.setData({
        recipe: mockRecipe,
        loading: false,
        basePrice: basePrice,
        totalPrice: (basePrice * this.data.quantity).toFixed(1)
      });
    });
  },

  // 模拟计算基础价格
  calculateBasePrice(recipe) {
    // 根据菜谱的热量或复杂度计算基础价格
    if (!recipe) return 0;
    
    // 简单的价格计算逻辑: 卡路里/10 + 难度系数
    let difficultyFactor = 0;
    switch(recipe.difficulty) {
      case '简单': difficultyFactor = 5; break;
      case '中等': difficultyFactor = 10; break;
      case '困难': difficultyFactor = 15; break;
      default: difficultyFactor = 5;
    }
    
    return Math.round((recipe.calories / 10 + difficultyFactor) * 10) / 10;
  },

  // 获取模拟菜谱详情
  getMockRecipeDetail(recipeId) {
    // 根据ID返回不同的菜谱数据
    const recipeData = {
      '1001': {
        id: '1001',
        title: "营养早餐三明治",
        imageUrl: "/images/discovers/png/sanmingzhi.png",
        description: "健康美味的三明治，含有丰富的蛋白质和维生素",
        calories: 350,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
        ingredients: [
          { name: "全麦面包", amount: "2片" },
          { name: "鸡蛋", amount: "1个" },
          { name: "生菜", amount: "2片" },
          { name: "番茄", amount: "2片" },
          { name: "低脂奶酪", amount: "1片" },
          { name: "火腿", amount: "1片" }
        ],
        steps: [
          "准备材料，清洗蔬菜",
          "锅中加少量油，煎鸡蛋至两面金黄",
          "烤面包至两面微焦",
          "在面包片上铺上生菜、番茄片、煎蛋、奶酪片和火腿",
          "盖上另一片面包，切成两半即可食用"
        ],
        nutritionFacts: {
          calories: 350,
          protein: "15g",
          fat: "12g",
          carbs: "35g",
          fiber: "5g"
        },
        tips: "可以根据个人口味添加少量番茄酱或蛋黄酱增加风味",
        price: 35.0
      },
      '1002': {
        id: '1002',
        title: "水果燕麦早餐杯",
        imageUrl: "/images/discovers/png/yanmaishuiguozhou.png",
        description: "富含膳食纤维的燕麦，搭配新鲜水果，营养均衡的早餐选择",
        calories: 280,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
        ingredients: [
          { name: "燕麦片", amount: "50g" },
          { name: "香蕉", amount: "1根" },
          { name: "草莓", amount: "5颗" },
          { name: "蓝莓", amount: "10颗" },
          { name: "无糖酸奶", amount: "150ml" },
          { name: "蜂蜜", amount: "1勺" }
        ],
        steps: [
          "将燕麦片倒入碗中，加入热水浸泡5分钟",
          "切好香蕉片，洗净草莓和蓝莓",
          "将浸泡好的燕麦倒入杯中，铺上一层酸奶",
          "依次加入香蕉片、草莓和蓝莓",
          "最后淋上蜂蜜即可食用"
        ],
        nutritionFacts: {
          calories: 280,
          protein: "10g",
          fat: "5g",
          carbs: "50g",
          fiber: "8g"
        },
        tips: "可以提前一晚准备，放入冰箱过夜更加方便",
        price: 28.0
      },
      '1003': {
        id: '1003',
        title: "牛油果全麦吐司",
        imageUrl: "/images/discovers/png/niuyouguo.png",
        description: "全麦面包搭配牛油果，美味健康的能量早餐",
        calories: 320,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
        ingredients: [
          { name: "全麦吐司", amount: "2片" },
          { name: "牛油果", amount: "1个" },
          { name: "西红柿", amount: "半个" },
          { name: "鸡蛋", amount: "1个" },
          { name: "芝麻", amount: "少量" },
          { name: "黑胡椒", amount: "少量" }
        ],
        steps: [
          "将吐司放入烤面包机烤至金黄",
          "煎鸡蛋，保持蛋黄半流动状态",
          "将牛油果切片，西红柿切片",
          "在烤好的吐司上依次铺上牛油果片、西红柿片和煎蛋",
          "撒上芝麻和黑胡椒提味即可"
        ],
        nutritionFacts: {
          calories: 320,
          protein: "12g",
          fat: "18g",
          carbs: "28g",
          fiber: "6g"
        },
        tips: "牛油果富含健康脂肪，能提供持久的饱腹感和能量",
        price: 32.0
      },
      '1004': {
        id: '1004',
        title: "蛋白能量早餐饼",
        imageUrl: "/images/discovers/png/danbaizhinengliangbing.png",
        description: "高蛋白早餐饼，晨跑前能量补充的理想选择",
        calories: 270,
        cookingTime: "15分钟",
        difficulty: "中等",
        category: "breakfast",
        ingredients: [
          { name: "鸡蛋", amount: "2个" },
          { name: "蛋白粉", amount: "20g" },
          { name: "燕麦片", amount: "30g" },
          { name: "香蕉", amount: "半根" },
          { name: "蓝莓", amount: "10颗" },
          { name: "椰子油", amount: "1勺" }
        ],
        steps: [
          "将鸡蛋打散，加入蛋白粉和燕麦片搅拌均匀",
          "加入捣碎的香蕉，继续搅拌",
          "平底锅中加入少量椰子油加热",
          "倒入面糊，小火煎至两面金黄",
          "加入蓝莓点缀即可食用"
        ],
        nutritionFacts: {
          calories: 270,
          protein: "20g",
          fat: "10g",
          carbs: "25g",
          fiber: "3g"
        },
        tips: "蛋白能量饼富含蛋白质，是健身人士理想的早餐选择",
        price: 27.0
      },
      '1005': {
        id: '1005',
        title: "清爽蔬菜早餐沙拉",
        imageUrl: "/images/discovers/png/qingjiaoshishu.png",
        description: "低脂健康的蔬菜沙拉，搭配酸奶酱，清新美味的早餐",
        calories: 200,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
        ingredients: [
          { name: "生菜", amount: "100g" },
          { name: "小番茄", amount: "5颗" },
          { name: "黄瓜", amount: "半根" },
          { name: "鸡胸肉", amount: "50g" },
          { name: "希腊酸奶", amount: "2勺" },
          { name: "橄榄油", amount: "1勺" }
        ],
        steps: [
          "将生菜洗净撕成小块，小番茄对半切，黄瓜切片",
          "鸡胸肉切丁煮熟备用",
          "将所有蔬菜和鸡胸肉放入碗中",
          "混合希腊酸奶和橄榄油制作酱料",
          "淋上酱料拌匀即可食用"
        ],
        nutritionFacts: {
          calories: 200,
          protein: "18g",
          fat: "8g",
          carbs: "12g",
          fiber: "4g"
        },
        tips: "早晨食用沙拉可以摄入充足的蔬菜纤维，帮助肠道健康",
        price: 25.0
      }
    };
    
    // 如果找不到对应ID的菜谱，返回默认菜谱
    return recipeData[recipeId] || {
      id: recipeId,
      title: "美味健康早餐",
      imageUrl: "/images/discovers/png/sanmingzhi.png",
      description: "营养均衡的早餐选择，能量满满的一天",
      calories: 300,
      cookingTime: "15分钟",
      difficulty: "简单",
      category: "breakfast",
      ingredients: [
        { name: "全麦面包", amount: "2片" },
        { name: "鸡蛋", amount: "1个" },
        { name: "生菜", amount: "2片" },
        { name: "番茄", amount: "2片" }
      ],
      steps: [
        "准备食材",
        "简单烹饪",
        "装盘即可食用"
      ],
      nutritionFacts: {
        calories: 300,
        protein: "12g",
        fat: "10g",
        carbs: "30g",
        fiber: "4g"
      },
      tips: "健康饮食从早餐开始",
      price: 30.0
    };
  },

  // 修改数量
  changeQuantity(e) {
    const type = e.currentTarget.dataset.type;
    let quantity = this.data.quantity;
    
    if (type === 'minus' && quantity > 1) {
      quantity -= 1;
    } else if (type === 'plus') {
      quantity += 1;
    }
    
    this.setData({
      quantity: quantity,
      totalPrice: (this.data.basePrice * quantity).toFixed(1)
    });
  },

  // 显示订购面板
  showOrderPanel() {
    this.setData({ showOrderPanel: true });
  },
  
  // 隐藏订购面板
  hideOrderPanel() {
    this.setData({ showOrderPanel: false });
  },

  // 立即订购
  placeOrder() {
    if (!this.data.recipe) return;
    
    // 检查用户是否登录
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (!userInfo || !token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/index/index'
        });
      }, 1500);
      return;
    }
    
    const userId = userInfo ? userInfo.userId : null;
    
    // 确保价格精确到两位小数
    const basePrice = parseFloat(this.data.basePrice).toFixed(2);
    const totalAmount = parseFloat(this.data.totalPrice).toFixed(2);
    
    // 获取当前时间戳，用于订单ID和时间记录
    const timestamp = new Date().getTime();
    
    const orderData = {
      id: 'order_' + timestamp, // 生成唯一订单ID
      recipeId: this.data.recipeId,
      recipeName: this.data.recipe.title,
      quantity: this.data.quantity,
      price: parseFloat(basePrice), // 确保是数字
      totalAmount: parseFloat(totalAmount), // 确保是数字
      orderTime: timestamp,
      userId: userId,  // 添加用户ID字段
      status: 'pending', // 添加状态字段：待支付
      imageUrl: this.data.recipe.imageUrl, // 添加菜品图片
      priceSource: this.data.priceSource || 'detail' // 记录价格来源
    };
    
    console.log('准备创建订单:', orderData);
    
    // 保存订单数据到本地
    let orders = wx.getStorageSync('orders') || [];
    orders.unshift(orderData);
    wx.setStorageSync('orders', orders);
    
    // 隐藏订购面板
    this.setData({ showOrderPanel: false });
    
    // 显示创建成功提示
    wx.showToast({
      title: '订单创建成功',
      icon: 'success',
      duration: 800
    });
    
    // 延迟跳转以确保Toast显示完成
    setTimeout(() => {
      const url = `/pages/order/payment/index?orderId=${orderData.id}`;
      console.log('跳转URL:', url);
      
      // 先跳转到"我的"页面，再跳转到订单支付页
      wx.switchTab({
        url: '/pages/my/index',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: url,
              success: () => {
                console.log('跳转支付页面成功');
              },
              fail: (err) => {
                console.error('跳转支付页面失败:', err);
                // 尝试直接跳转
                setTimeout(() => {
                  wx.navigateTo({
                    url: url,
                    fail: () => {
                      wx.showToast({
                        title: '无法打开支付页面',
                        icon: 'none',
                        duration: 2000
                      });
                    }
                  });
                }, 300);
              }
            });
          }, 200);
        },
        fail: (err) => {
          console.error('跳转我的页面失败:', err);
          // 显示错误信息
          wx.showToast({
            title: '跳转失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }, 200); // 延迟时间
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
})